/**
 *WangGANG
 *2018/8/6
 */
package getUrl

import (
	"fmt"
	"io/ioutil"
	"strings"
	"bytes"
	"net/http"
)

const indexName  = "body" //查找的字符

func Fetcha(url string) {
	counts := 0
	fmt.Println("---------------------------------------------------------")
	ch := make(chan string)
	go fetch(url,ch) //启动一个goroutine
	//关闭通道
	defer close(ch)
	//获取通道内容
	book := <-ch
	//打印通道内容，下一步可以修改为对内容进行读取并对内容进行分析
	fmt.Println(strings.Split(book," "))
	for _,urlContent := range strings.Split(book," "){
		if strings.Index(urlContent,indexName) > 0 {
			 counts++
		}
	}
	fmt.Println("counts = ",counts)

}


func fetch(url string,ch chan <- string){
	//start := time.Now()
	resp,err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)//发送到通道ch
	}
	book,err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		ch <- fmt.Sprintf("while reading %s : %v ",url,err)
	}
	books := bytes.Fields(book)//返回将字符串按照空白分割的多个子切片
	//secs := time.Since(start).Seconds()
	ch <- fmt.Sprintf("%s",books)

}
